package com.gitee.kooder.code;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.jgit.api.CloneCommand;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.TransportCommand;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;

import java.io.File;
import java.io.IOException;

public class Main {
    public static void main(String[] args) throws GitAPIException, IOException {
        String fromUrl = "https://git.betawm.com/tech/Beta.ActivityCenterApi";
        String baseBranch = "dev-20210406";
        File toPath = new File("C:/tmp/git/");
        System.out.println("项目(" + fromUrl + ")配置的分支：" + baseBranch);
        if (StringUtils.isBlank(baseBranch)) {
            baseBranch = "master";
        }
        //先摘取master分支，再取获取的分支，然后切过去
        CloneCommand cloneCommand = Git.cloneRepository()
                .setURI(fromUrl)
                .setDirectory(toPath)
                .setCloneAllBranches(true);
        autoSetCredential(cloneCommand);
        cloneCommand.setCloneSubmodules(false);
        cloneCommand.setBare(true);//只克隆 git 数据库，不克隆文件
        Git git = cloneCommand.call();


        //切换分支
        git.close();
        FileUtils.forceDelete(toPath);
        //先摘取master分支，再取获取的分支，然后切过去
        cloneCommand = Git.cloneRepository()
                .setURI(fromUrl)
                .setDirectory(toPath)
                .setBranch(baseBranch.trim())
                .setCloneAllBranches(true);
        autoSetCredential(cloneCommand);
        cloneCommand.setCloneSubmodules(false);
        cloneCommand.setBare(true);//只克隆 git 数据库，不克隆文件
        git = cloneCommand.call();
        git.close();
    }

    private static void autoSetCredential(TransportCommand command) {
        command.setCredentialsProvider(new UsernamePasswordCredentialsProvider("fctao", "taofuchok"));
    }
}
